<template>
  <div class="app-container">
    <el-card>

      <el-steps :active="parseInt(active)" finish-status="success">
        <el-step title="基础信息" />
        <el-step title="邮寄信息" />
        <el-step title="商品规格" />
        <el-step title="商品详情" />
        <el-step title="商品分类" />
      </el-steps>

      <el-tabs v-model="active" tab-position="left" style="margin-top: 40px">
        <el-tab-pane label="基础信息">
          <div style="width: 60%">
            <el-form
              ref="goods"
              :model="goods"
              :rules="rules"
              label-width="100px"
            >

              <el-form-item label="商品封面" 　 prop="cover">
                <ImageUploader
                  :url="goods.coverUrl"
                  :path="goods.cover"
                  @ok="function(data){
                    goods.coverUrl=data.url
                    goods.cover=data.path
                  }"
                />
              </el-form-item>
              <el-form-item label="轮播图" 　 prop="sliders">
                <el-upload
                  :action="`${baseUrl}`+'/pp/file/upload'"
                  :headers="headers()"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handlePictureSuccess"
                  :file-list="goods.fileList"
                >
                  <i class="el-icon-plus" />
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>

              <el-form-item label="商品名称" 　 prop="name">
                <el-row>
                  <el-col :span="18">
                    <el-input v-model="goods.name" placeholder="请输入商品名称" />
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="商品简介" 　 prop="intro">
                <el-row>
                  <el-col :span="18">
                    <el-input v-model="goods.intro" placeholder="请输入商品简介" type="textarea" />
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="商品售后" 　 prop="ensure">
                <el-row>
                  <el-col :span="18">
                    <el-input v-model="goods.ensure" placeholder="请输入商品售后" type="textarea" />
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="商品参数" 　 prop="params">
                <el-row v-for="(param,index) in goods.paramsArr">
                  <el-col :span="8">
                    <el-input v-model="param.key" placeholder="请输入参数名称" />
                  </el-col>
                  <el-col :span="2" style="text-align: center">-</el-col>
                  <el-col :span="8">
                    <el-input v-model="param.value" placeholder="请输入参数值" />
                  </el-col>

                  <el-col v-if="goods.paramsArr.length>1" :span="3">
                    <el-button
                      @click.native.prevent="function(){
                        goods.paramsArr.splice(index,1)
                      }"
                    >删除
                    </el-button>
                  </el-col>

                  <el-col v-if="index=== goods.paramsArr.length-1" :span="3">
                    <el-button @click.native.prevent="addParam">添加</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click.native.prevent="addSave">保存下一步</el-button>
              </el-form-item>
            </el-form>
          </div>

        </el-tab-pane>
        <el-tab-pane label="邮寄信息">
          <div style="width: 60%">
            <el-form
              ref="postage"
              :model="postage"
              :rules="rules"
              label-width="100px"
            >

              <el-form-item label="发货地" 　 prop="postFrom">
                <el-row>
                  <el-col :span="18">
                    <el-input
                      v-model="postage.postFrom"
                      placeholder="请输入发货地"
                    />
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="单件运费" 　 prop="postage">
                <el-row>
                  <el-col :span="18">
                    <el-input
                      v-model="postage.postage"
                      :disabled="postage.postageIfFree"
                      type="number"
                      placeholder="请输入单件运费"
                    />
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="包邮设置" 　 prop="postageIfFree">
                <el-row>
                  <el-col :span="18">
                    <el-checkbox v-model="postage.postageIfFree">是否包邮</el-checkbox>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="满额设置" 　 prop="postageIfFree">
                <el-row>
                  <el-col :span="18">
                    <el-checkbox v-model="postage.postageInRuleIfFree" :disabled="postage.postageIfFree">是否满额免邮
                    </el-checkbox>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="合并设置" 　 prop="postageSkuIfMerge">
                <el-row>
                  <el-col :span="18">
                    <el-checkbox v-model="postage.postageSkuIfMerge" :disabled="postage.postageIfFree">
                      是否同规格合并邮寄
                    </el-checkbox>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click.native.prevent="postageSave">保存下一步</el-button>
              </el-form-item>

            </el-form>
          </div>
        </el-tab-pane>

        <el-tab-pane label="商品规格">
          <div style="width: 100%">
            <el-form
              ref="attrs"
              :model="attrs"
              label-width="100px"
            >
              <el-form-item label="属性">
                <el-row :gutter="10">
                  <el-col :span="5">
                    <el-input
                      v-model="attrs.attrName"
                      size="small"
                      placeholder="请输入属性名称"
                      @keyup.enter.native="addAttrItem"
                    />
                  </el-col>
                  <el-col :span="3">
                    <el-button size="small" plain type="primary" @click.native.prevent="addAttrItem">添加属性</el-button>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item
                v-for="(attr,index) in attrs.attrs"
                :label="attr.name"
              >
                <el-row>
                  <el-tag
                    v-for="(tag,indexTag) in attr.vals"
                    :key="tag"
                    style="margin-right: 10px"
                    closable
                    :disable-transitions="false"
                    @close="function(){
                      attr.vals.splice(indexTag,1)
                    }"
                  >
                    {{ tag }}
                  </el-tag>

                  <el-input
                    v-model="attr.val"
                    style="width: 150px;margin-right: 10px"
                    class="input-new-tag"
                    size="small"
                    placeholder="填写可选属性值"
                    @keyup.enter.native="addAttrItemVal(attr)"
                    @blur="addAttrItemVal(attr)"
                  />

                  <el-button
                    type="delete"
                    plain
                    size="small"
                    @click.native.prevent="function(){
                      attrs.attrs.splice(index)
                    }"
                  >删除属性
                  </el-button>

                </el-row>
              </el-form-item>

              <el-divider content-position="left">编辑属性</el-divider>

              <el-form-item
                v-for="(attr,index) in attrs.attrs"
                :label="attr.name"
              >
                <el-radio-group v-model="attr.choosed" size="small">
                  <el-radio-button
                    v-for="(val,valIndex) in attr.vals"
                    :key="val"
                    :label="val"
                  />
                </el-radio-group>

              </el-form-item>

              <el-form-item>
                <el-tooltip :disabled="!addSkuAble" class="item" effect="light" content="请选择所有属性" placement="bottom">
                  <el-button
                    :disabled="!addSkuAble"
                    type="primary"
                    plain
                    size="small"
                    @click.native.prevent="addSku"
                  >添加规格sku
                  </el-button>
                </el-tooltip>
              </el-form-item>

              <el-form-item>
                <el-table :data="skus.skus">
                  <el-table-column type="index" label="序号" />

                  <el-table-column v-slot="scope" label="封面">
                    <template>
                      <ImageUploader
                        width="80px"
                        height="80px"
                        :url="scope.row.coverUrl"
                        :path="scope.row.cover"
                        @ok="function(data){
                          scope.row.coverUrl=data.url
                          scope.row.cover=data.path
                        }"
                      />
                    </template>
                  </el-table-column>

                  <el-table-column v-slot="scope" label="规格">
                    <template>
                      <el-tag v-for="(k,v) in scope.row.attrInfo">
                        {{ k }}
                      </el-tag>
                    </template>
                  </el-table-column>

                  <el-table-column v-slot="scope" label="原价">
                    <el-input v-model="scope.row.originPrice" size="small" />
                  </el-table-column>

                  <el-table-column v-slot="scope" label="售价">
                    <el-input v-model="scope.row.price" size="small" />
                  </el-table-column>

                  <el-table-column v-slot="scope" label="库存">
                    <el-input v-model="scope.row.stock" size="small" />
                  </el-table-column>

                  <el-table-column v-slot="scope" label="操作">
                    <el-button plain type="primary" size="small" @click.native.prevent="skus.skus.splice(scope.$index,1)">删除</el-button>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-divider content-position="left">编辑规格</el-divider>
              <el-form-item>
                <el-button type="primary" @click.native.prevent="saveAttrsAndSkus">保存下一步</el-button>

              </el-form-item>

            </el-form>
          </div>
        </el-tab-pane>

        <el-tab-pane label="商品详情">
          <div style="width: 60%">
            <el-form :model="detailIntro">
              <div>
                <tinymce ref="tinymce" v-model="detailIntro.detailIntro" :height="300" />
              </div>

              <el-form-item>
                <el-button type="primary" @click.native.prevent="saveDetailIntro">保存下一步</el-button>
              </el-form-item>
            </el-form>
          </div>

        </el-tab-pane>
        <el-tab-pane label="商品分类">
          <div style="width: 60%">
            <el-form
              ref="categorize"
              :model="categorize"
              :rules="rules"
              label-width="100px"
            >

              <el-form-item label="普通分类" 　>
                <el-row>
                  <el-col :span="18">
                    <el-select v-model="categorize.normalIds" multiple>
                      <el-option
                        v-for="cate in normalCates"
                        :key="cate.cateId"
                        :value="cate.cateId"
                        :label="cate.name"
                      />
                    </el-select>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="推荐分类" 　>
                <el-row>
                  <el-col :span="18">
                    <el-select v-model="categorize.recommendIds" multiple>
                      <el-option
                        v-for="cate in recommendCates"
                        :key="cate.cateId"
                        :value="cate.cateId"
                        :label="cate.name"
                      />
                    </el-select>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click.native.prevent="saveCategorize">保存下一步</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>

    </el-card>
  </div>
</template>

<script>
import ImageUploader from '@/pp-components/ImageUploader.vue'
import { getToken } from '@/utils/auth'
import { detail, add, edite, postageUpdate, attrUpdate
  , skuUpdate, detailIntroUpdate, categorizeUpdate } from '@/api/pp/goods/goods'
import { getList as getCateList } from '@/api/pp/goods/catgorize'
import Tinymce from '@/components/Tinymce'

export default {
  components: { ImageUploader, Tinymce },
  data() {
    return {
      categorize: {
        normalIds: [],
        recommendIds: []
      },
      normalCates: [],
      recommendCates: [],
      baseUrl: process.env.VUE_APP_API_HOST,
      rules: {
        name: [{ required: true, trigger: 'blur', message: '商品名称不为空' }],
        postFrom: [{ required: true, trigger: 'blur', message: '发货地不为空' }],
        cover: [{ required: true, trigger: 'blur', message: '封面不为空' }],
        intro: [{ required: true, trigger: 'blur', message: '商品简介不为空' }]
      },
      active: '0',
      goods: {
        goodsId: undefined,
        name: undefined,
        cover: undefined,
        sliders: [],
        intro: undefined,
        params: {},
        ensure: undefined,
        coverUrl: undefined,
        fileList: [],
        paramsArr: [{ key: null, value: null }]
      },
      postage: {
        postage: 0,
        postFrom: undefined,
        postageIfFree: false,
        postageInRuleIfFree: false,
        postageSkuIfMerge: false
      },
      attrs: {
        attrs: [], // {name:"",vals:],val:null,choosed:null}
        attrName: undefined
      },
      skus: {
        skus: [] // {stock:0,cover:null,originPrice:null,price:null,attrInfo:{},}
      },
      detailIntro: {
        detailIntro: undefined
      },

      dialogImageUrl: undefined,
      dialogVisible: false
    }
  },
  computed: {
    addSkuAble() {
      if (!this.attrs.attrs || this.attrs.attrs.length === 0) {
        return false
      }
      for (let i = 0; i < this.attrs.attrs.length; i++) {
        if (!this.attrs.attrs[i].choosed) {
          return false
        }
      }
      return true
    }
  },
  mounted() {
    const goodsId = parseInt(this.$route.query.id)
    this.getCateList()
    if (goodsId) {
      this.goods.goodsId = goodsId
      detail(this.goods.goodsId).then(res => {
        this.goods.sliders = res.data.sliders
        this.goods.name = res.data.name
        this.goods.cover = res.data.cover
        this.goods.coverUrl = res.data.coverUrl
        this.goods.intro = res.data.intro
        this.goods.ensure = res.data.ensure
        this.goods.paramsArr = []
        Object.keys(res.data.params).forEach(k => {
          this.goods.paramsArr.push({
            key: k, value: res.data.params[k]
          })
        })
        this.goods.paramsArr.push({ key: null, value: null })
        res.data.slidersUrl.forEach(e => {
          this.goods.fileList.push({
            url: e,
            name: e
          })
        })

        // 邮寄信息
        this.postage.postage = res.data.postage
        this.postage.postFrom = res.data.postFrom
        this.postage.postageIfFree = res.data.postageIfFree
        this.postage.postageInRuleIfFree = res.data.postageInRuleIfFree
        this.postage.postageSkuIfMerge = res.data.postageSkuIfMerge

        this.attrs.attrs = res.data.attrs
        this.skus.skus = res.data.skus

        // this.detailIntro.detailIntro=res.data.detailIntro
        this.$refs.tinymce.setContent(res.data.detailIntro)

        // res.data.catIds
        this.categorize.normalIds =
          res.data.catIds.filter(e => this.normalCates.some(c => c.cateId === e))

        this.categorize.recommendIds =
          res.data.catIds.filter(e => this.recommendCates.some(c => c.cateId === e))
      })
    }
  },
  methods: {
    async getCateList() {
      await getCateList(null).then(res => {
        this.normalCates = res.data.list.filter(e => e.type === 1)
        this.recommendCates = res.data.list.filter(e => e.type === 2)
      })
    },
    saveCategorize() {
      categorizeUpdate({
        goodsId: this.goods.goodsId,
        catIds: [
          ... this.categorize.normalIds,
          ... this.categorize.recommendIds
        ]
      }).then(res => {
        this.$msgOk(res)
        this.toNext()
      })
    },
    saveDetailIntro() {
      detailIntroUpdate({
        goodsId: this.goods.goodsId,
        detailIntro: this.detailIntro.detailIntro
      }).then(res => {
        this.$msgOk(res)
        this.toNext()
      })
    },
    saveAttrsAndSkus() {
      if (!this.attrs.attrs || this.attrs.attrs.length === 0) {
        this.$msgFail('请添加属性')
        return
      }
      for (let i = 0; i < this.attrs.attrs.length; i++) {
        if (!this.attrs.attrs[i].vals || this.attrs.attrs[i].vals.length === 0) {
          this.$msgFail('请添加属性可选值')
          return
        }
      }
      if (!this.skus.skus || this.skus.skus.length === 0) {
        this.$msgFail('请添加规格')
        return
      }
      for (let i = 0; i < this.skus.skus.length; i++) {
        if (!this.skus.skus[i].price) {
          this.$msgFail('请填写规格的价格')
          return
        }
        if (!this.skus.skus[i].cover) {
          this.$msgFail('请上传规格封面')
          return
        }
      }

      const goodsId = this.goods.goodsId
      attrUpdate({
        goodsId,
        attrs: this.attrs.attrs
      }).then(res => {
        skuUpdate({
          goodsId,
          skus: this.skus.skus
        }).then(res => {
          this.$msgOk(res)
          this.toNext()
        })
      })
    },
    addSku() {
      // this.skus.skus.
      if (this.attrs.attrs.some(e => !e.choosed)) {
        this.$msgFail('请选择属性值')
        return
      }
      const attrInfo = {}
      this.attrs.attrs.forEach(e => {
        attrInfo[e.name] = e.choosed
      })
      this.skus.skus.push({
        attrInfo,
        stock: 0, cover: null, originPrice: null, price: null
      })
      this.attrs.attrs.forEach(e => {
        e.choosed = null
      })
    },
    addAttrItemVal(attr) {
      if (!attr.val || attr.val.trim().length === 0) {
        return
      }
      attr.vals.push(attr.val)
      attr.val = null
    },
    addAttrItem() {
      if (!this.attrs.attrName ||
        this.attrs.attrName.trim().length === 0) {
        return
      }
      this.attrs.attrs.push({
        name: this.attrs.attrName,
        vals: []
      })
      this.attrs.attrName = undefined
    },
    headers() {
      return {
        Authorization: getToken()
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      for (let i = 0; i < this.goods.sliders.length; i++) {
        if (file.response && file.response.data.path === this.goods.sliders[i] ||
          file.url && file.url.includes(this.goods.sliders[i])
        ) {
          this.goods.sliders.splice(i, 1)
        }

        /*  if( || this.goods.sliders[i]===file.response.data.path){
           this.goods.sliders.splice(i,1)
         } */
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handlePictureSuccess(res, file) {
      console.log(res)
      console.log(file)
      this.goods.sliders.push(res.data.path)
    },
    addParam() {
      this.goods.paramsArr.push({ key: null, value: null })
    },
    postageSave() {
      if (!this.goods.goodsId) {
        this.$msgFail('请先保存商品')
        return
      }
      const goodsId = this.goods.goodsId
      this.$refs.postage.validate().then(res => {
        postageUpdate({
          ...this.postage,
          goodsId
        }).then(res => {
          this.$msgOk(res)
          this.toNext()
        })
      })
    },
    addSave() {
      this.$refs.goods.validate().then(() => {
        const params = {}
        this.goods.paramsArr.forEach(e => {
          if (e.key && e.value) {
            params[e.key] = e.value
          }
        })
        this.goods.params = params
        if (this.goods.goodsId) {
          edite(this.goods).then(res => {
            this.$msgOk(res)
            this.toNext()
          })
        } else {
          add(this.goods).then(res => {
            this.$msgOk(res)
            this.toNext()
          })
        }
      })
    },
    toNext() {
      this.active = (parseInt(this.active) + 1) + ''
    }
  }
}
</script>

<style scoped>

</style>
